<?php

/**
 * 收入确认信息仓库
 * @author zhoud 2018-02-02
 */
namespace common\repositories\myhtsq;

use common\entities\myhtsq\BussAccountTypesEntity;
use common\entities\myhtsq\ContractRevenueEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use Yii;
use yii\db\Query;
use Exception;
use common\error\ErrorCode;
use common\entities\ContractEntity;
use common\entities\myhtsq\RevenueRecognitionEntity;
use common\models\myhtsq\RevenueRecognitionModel;


class RevenueRecognitionRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 数组分页函数  核心函数  array_slice
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
     * $count   每页多少条数据
     * $page   当前第几页
     * $array   查询出来的所有数组
     * order 0 - 不变     1- 反序
     */

    public static function pageArray($count,$page,$array,$order){

        global $countPage; #定全局变量
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start=($page-1)*$count; #计算每次分页的开始位置
        if($order==1){
            $array=array_reverse($array);  #函数返回翻转顺序的数组
        }
        $totals=count($array);
        $countPage=ceil($totals/$count); #计算总页面数
        return array_slice($array,$start,$count);#返回查询数据
    }

    private static function timeToDay($time)
    {
        return ($time)/(3600*24);
    }

    private static function summaryRecognitionAmount($revenueId){

        $recognitionAmount = 0;
        $revenueRecognitionListAll = self::getRevenueRecognitionListByRevenueId($revenueId);
        foreach ($revenueRecognitionListAll as $value){
            $recognitionAmount += $value['recognition_amount'];
        }

        return $recognitionAmount;

    }

    public static function summaryRecognitionAmountAfterThis($revenueId,$recognitionEnd){

        $recognitionAmount = 0;
        $revenueRecognitionListAll = self::getRevenueRecognitionListByRevenueIdRecognitionEnd($revenueId,$recognitionEnd);
        foreach ($revenueRecognitionListAll as $value){
            $recognitionAmount += $value['recognition_amount'];
        }

        return $recognitionAmount;

    }

    public static function summaryRecognitionAmountBeforeThis($revenueId,$recognitionBegin,$recognitionEnd,$createdOn){

        $recognitionAmount = 0;
        $revenueRecognitionListAll = self::getRecognitionBeforeThisRecognitionEndContain($revenueId,$recognitionBegin,$recognitionEnd,$createdOn);
        foreach ($revenueRecognitionListAll as $value){
            $recognitionAmount += $value['recognition_amount'];
        }

        return $recognitionAmount;

    }

    private static function summaryReceivableAmount($receivables){

        $receivableAmount = 0;
        foreach ($receivables as $record){
            $receivableAmount += $record['receivable_amount'];
        }

        return $receivableAmount;

    }

    private static function summaryPaymentAmount($receivables){

        $paymentAmount = 0;
        foreach ($receivables as $record){

            $paymentList = ContractReceivableRepository::getPaymentByContractIdReceivableId($record['contract_id'],$record['receivable_id']);

            foreach ($paymentList as $list){
                $paymentAmount += $list['payment_amount'];
            }

        }

        return $paymentAmount;

    }

    public static function getPaymentByContractIdReceivableId($contractId,$receivableId){
        return ContractReceivableRepository::getPaymentByContractIdReceivableId($contractId,$receivableId);
    }

    private static function revenueRecognitionRecord($recognitionBegin,$recognitionEnd,$revenueList,$type)
    {
        //收入结转成功与失败记录
        $addRevenueRecognitionList = [
            'recognition_id'=>[],
            'revenue_id'=>[],
        ];

        $thisRecognitionBegin = self::dateToYmd($recognitionBegin);
        $thisRecognitionEnd = self::dateToYmd($recognitionEnd);

        //取出所有收入计算每条当期累计可结转收入
        foreach ($revenueList as $item){
            $equityBegin = self::dateToYmd($item['BeginOn']);
            $equityEnd = self::dateToYmd($item['EndOn']);
            $establishTime = self::dateToYmd($item['EstablishTime']);
            $amount = $item['amount'];


//            if($type && $item['type_name'] !== $type){//按结转操作结转对应类型收入
//                continue;
//            }

            if($item['close_status'] !== '1'){//收入必须未关闭
                continue;
            }

            if($establishTime > $thisRecognitionEnd){//开通时间必须小等于本期结转末期
                continue;
            }
//            $revenueRecognitions = RevenueRecognitionRepository::getRevenueRecognitionListByRevenueId($item['revenue_id']);
//            $totalRevenueRecognitionAmount = self::summaryAmount('recognition_amount',$revenueRecognitions);//总的已确认收入
            $totalRevenueRecognitionAmount = RevenueRecognitionRepository::getSumRevenueRecognition($item['revenue_id']);
            $scale = ContractRevenueRepository::calculateScaleByRecognitionType($thisRecognitionBegin,$thisRecognitionEnd,$equityBegin,$equityEnd,$establishTime,$item['type_name']);
            //本期可以结转金额
            //要取本期之前的金额
            $thisPeriodSureRecognitionAmount = ContractRevenueRepository::totalCanRevenueAmount($amount,$totalRevenueRecognitionAmount,$scale,$thisRecognitionEnd,$equityBegin,$equityEnd,$establishTime,$item['type_name']);
            $totalRecognitionAmountAfterThis = self::summaryRecognitionAmountAfterThis($item['revenue_id'],$thisRecognitionEnd);
            $lastRecognizedAmount = $totalRevenueRecognitionAmount - $totalRecognitionAmountAfterThis;

            //收入下是否有结转记录
            $recognitions = self::getTermRecognition($item['revenue_id'],$thisRecognitionBegin,$thisRecognitionEnd);

            //新增结转金额记录
            $revenueRecognitionModel = new RevenueRecognitionModel(['scenario' => 'saveRevenueRecognition']);

            $revenueRecognitionModel->revenue_id = $item['revenue_id'];
            $revenueRecognitionModel->contract_id = $item['contract_id'];
            $revenueRecognitionModel->recognition_amount = $thisPeriodSureRecognitionAmount;
            $revenueRecognitionModel->last_period_total_confirm_amount = $lastRecognizedAmount;
            $revenueRecognitionModel->this_period_confirm_total_amount = $lastRecognizedAmount+$thisPeriodSureRecognitionAmount;
            $revenueRecognitionModel->recognition_begin = $thisRecognitionBegin;
            $revenueRecognitionModel->recognition_end = $thisRecognitionEnd;
            $revenueRecognitionModel->recognition_date = date("Y-m-d H:i:s");
            $revenueRecognitionModel->recognition_by = \Yii::$app->user->identity->username;
            $revenueRecognitionModel->recognitioner_guid = \Yii::$app->user->identity->userguid;
            // 开启事务
            $configDataBase = ContractEntity::getDb();
            $trans = $configDataBase->beginTransaction();
            try{
                //结转检查
                $entity = ContractRevenueRepository::getContractRevenueInfoByRevenueId($item['revenue_id']);
                $check = $entity->carryOverCheck($revenueRecognitionModel->getAttributes());
                if($check){
                    //增加确认收入
                    if(empty($recognitions)){
                        $ret = self::addRevenueRecognition($revenueRecognitionModel);
                    }else{
                        $revenueRecognitionModel->recognition_id = $recognitions['recognition_id'];
                        $ret = self::updateRevenueRecognition($revenueRecognitionModel);
                    }

                    if($ret === false){
                        $trans->rollBack();
                        return false;
                    }
                }else{
                    $trans->rollBack();
                    return false;
                }
//                $recognitionsAddAfter = RevenueRecognitionRepository::getRevenueRecognitionListByRevenueId($item['revenue_id']);
//
//                $totalRecognitionAmountAddAfter = self::summaryAmount('recognition_amount',$recognitionsAddAfter);
                $totalRecognitionAmountAddAfter = RevenueRecognitionRepository::getSumRevenueRecognition($item['revenue_id']);
                if($totalRecognitionAmountAddAfter >= $amount){//收入确认金额大于等于收入金额关闭收入项
                    $ret = ContractRevenueRepository::closeRevenueByRevenueId($item['revenue_id'],3);//自动关闭收入项
                    if($ret === false){
                        $trans->rollBack();
                        return false;
                    }
                }
                $trans->commit();
            }catch(\Exception $e){
                $trans->rollBack();
                return false;
            }
            if($ret !== false){
                $addRevenueRecognitionList['recognition_id'][] = $ret;
                $addRevenueRecognitionList['success'] += 1;
            }else{
                $addRevenueRecognitionList['revenue_id'][] = $item['revenue_id'];
                $addRevenueRecognitionList['fail'] += 1;
            }
        }

        return $addRevenueRecognitionList;
    }

    private static function dateToYmd($date){
        return substr($date, 0, -9);
    }

    private static function summaryAmount($field,$list){

        $amount = 0;

        foreach ($list as $item){
            $amount += $item[$field];
        }

        return $amount;
    }

    /**
     * 新增确认收入
     * @param \common\models\myhtsq\RevenueRecognitionModel $revenueRecognitionModel
     * @return boolean|string 失败返回false，成功返回新增的确认收入Id
     */
    public static function addRevenueRecognition($revenueRecognitionModel)
    {

        $entity = new RevenueRecognitionEntity();

        $entity->setAttributes($revenueRecognitionModel->attributes);
        $entity->recognition_id = StringHelper::uuid();
        if($entity->save()) {
            return $entity->primaryKey;
        }else{
            return false;
        }

    }

    /**
     * 修改确认收入
     * @param \common\models\myhtsq\RevenueRecognitionModel $revenueRecognitionModel
     * @return boolean|string 失败返回false，成功返回发票Id
     */
    public static function updateRevenueRecognition($revenueRecognitionModel)
    {

        try {
            $entity = RevenueRecognitionEntity::find()->where(['recognition_id' => $revenueRecognitionModel->recognition_id])->one();
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_RECOGNITION_SAVE_FAIL);
            }

            $entity->recognition_amount = $revenueRecognitionModel->recognition_amount;
            $result = $entity->update();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_RECOGNITION_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 依据收入id查询确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getRevenueRecognitionListByRevenueId($revenueId)
    {
        return RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'is_del'=>1])->all();
    }

    /**
     * 依据收入id查询确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getSumRevenueRecognition($revenueId)
    {
        return floatval(RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'is_del'=>1])->sum('recognition_amount'));
    }

    /**
     * 获取收入项累计已确认金额
     * @param $revenueId
     * @return mixed
     */
    public static function getTotalConfirmedAmount($revenueId)
    {
        $sum = RevenueRecognitionEntity::find()->where(['revenue_id' => $revenueId,'is_del'=>1])->sum('recognition_amount');
        return floatval($sum?$sum:0);
    }
    /**
     * 获取指定收入项最近一次转结记录
     * @param $revenueId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getLatestCarryoverByRevenueId($revenueId){
        return RevenueRecognitionEntity::find()->where(['revenue_id' => $revenueId,'is_del'=>1])->orderBy('recognition_end desc')->one();
    }


    public static function getRecognitionByRecognitionId($recognitionId)
    {
        return RevenueRecognitionEntity::find()->where(['recognition_id'=>$recognitionId,'is_del'=>1])->one();
    }

    /**
     * 依据收入日期查询确认收入
     * @param string $recognitionBegin,$recognitionEnd 起止时间
     * @return array
     */
    public static function getRevenueRecognitionByRecognitionDate($recognitionBegin,$recognitionEnd)
    {
        return RevenueRecognitionEntity::find()->where(['recognition_begin'=>$recognitionBegin,'recognition_end'=>$recognitionEnd,'is_del'=>1])->one();
    }

    /**
     * 依据收入id&结转期查询确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getRevenueRecognitionListByRevenueIdRecognitionEnd($revenueId,$recognitionEnd)
    {
        return RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'is_del'=>1])->andWhere(['>=', 'recognition_end', $recognitionEnd])->all();
    }

    /**
     * 依据收入id&结转期查询上期累计确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getRecognitionBeforeThisRecognitionEnd($revenueId,$recognitionEnd)
    {
        return RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'is_del'=>1])->andWhere(['<', 'recognition_end', $recognitionEnd])->all();
    }

    /**
     * 依据收入id&结转期查询上期累计确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getRecognitionBeforeThisRecognitionEndContain($revenueId,$recognitionBegin,$recognitionEnd,$createdOn)
    {
        return RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'recognition_begin'=>$recognitionBegin ,'recognition_end'=>$recognitionEnd,'is_del'=>1])->andWhere(['<=', 'created_on',$createdOn])->all();
    }

    /**
     * 依据收入id&结转期查询确认收入
     * @param string $revenueId 收入ID
     * @return array
     */
    public static function getThisRecognitionList($revenueId,$recognitionBegin,$recognitionEnd){
        return RevenueRecognitionEntity::find()->where(['revenue_id'=>$revenueId,'is_del'=>1,'recognition_begin'=>$recognitionBegin,'recognition_end'=>$recognitionEnd])->all();
    }


    /**
     * 依据收入id查询确认收入含本期累计结转记录&上期累计结转记录
     * @param string $revenueId 收入ID
     * @return array``
     */
    public static function getRecognitionLastUnionThisIssueByRevenueId($revenueId)
    {
        $query = new Query();
        $result = $query->select(["*"])
            ->from('myscrm_revenue_recognition recognition')
            ->where(['revenue_id'=>$revenueId,'is_del'=>1])
            ->all(ContractEntity::getDb());

        //增加上期累计确认收入&本期累计确认收入&缺少收入来源判断
        foreach ($result as &$item){

            $totalRecognitionAmount = self::summaryRecognitionAmount($item['revenue_id']);
            //依据大于等当前结转期之后的进行汇总
            #结转末期相同汇总但是结转初期是否有可能不同算做不同结转期？这样逻辑有问题
            $issueTotalRecognitionAmountAfterThis = self::summaryRecognitionAmountAfterThis($item['revenue_id'],$item['recognition_end']);
            $thisIssueTotalRecognitionAmount = self::summaryRecognitionAmountBeforeThis($item['revenue_id'],$item['recognition_begin'],$item['recognition_end'],$item['created_on']);
            //收入下所有结转金额汇总 - 当前结转期之后的进行汇总 = 上期累计汇总
            $lastIssueTotalRecognitionAmount = $totalRecognitionAmount - $issueTotalRecognitionAmountAfterThis;

            $item['last_issue_total_recognition_amount'] = $lastIssueTotalRecognitionAmount;
            $item['this_issue_total_recognition_amount'] = $lastIssueTotalRecognitionAmount + $thisIssueTotalRecognitionAmount;
            $item['revenue_source'] = empty($lastIssueTotalRecognitionAmount)?'本期新增':'上期结转';

        }

        return $result;
    }

    /**
     * 组建查找收入SQL
     * @param string $where
     * @param \common\models\myhtsq\RevenueRecognitionModel $revenueRecognitionModel
     * @return array
     */
    private static function __buildGetRecognitionRevenueContractWhereSql($where,$revenueRecognitionModel)
    {
        $params = [];

        if (isset($revenueRecognitionModel->recognition_begin) && !empty($revenueRecognitionModel->recognition_begin)) {
            $where = $where . ' and (recognition.recognition_begin >= :begin_on)';
            $params[':begin_on'] = $revenueRecognitionModel->recognition_begin . ' 00:00:00';
        }

        if (isset($revenueRecognitionModel->recognition_end) && !empty($revenueRecognitionModel->recognition_end)) {
            $where = $where . ' and (recognition.recognition_end <= :end_on)';
            $params[':end_on'] = $revenueRecognitionModel->recognition_end . ' 00:00:00';
        }

        /*if (isset($revenueRecognitionModel->recognition_end) && !empty($revenueRecognitionModel->recognition_end)) {
            $where = $where . ' and (recognition.recognition_end in '.self::arrToIn($revenueRecognitionModel->recognition_end);
        }*/

        if (isset($revenueRecognitionModel->close_status) && !empty($revenueRecognitionModel->close_status)) {
            $where = $where . ' and (revenue.close_status = :close_status)';
            $params[':close_status'] = $revenueRecognitionModel->close_status;
        }

        if (isset($revenueRecognitionModel->contract_status) && !empty($revenueRecognitionModel->contract_status)) {
            $where = $where . ' and (manage.contract_status = :contract_status)';
            $params[':contract_status'] = $revenueRecognitionModel->contract_status;
        }

        if (isset($revenueRecognitionModel->search_key) && !empty($revenueRecognitionModel->search_key)) {
            $where = $where . " and (revenue.income_code like CONCAT('%', :income_code, '%'))";
            $params[':income_code'] = $revenueRecognitionModel->search_key;
        }

        return ['where' => $where, 'params' => $params];
    }

    private static function arrToIn($arr)
    {

        $str = '(';
        foreach ($arr as $value){
            $str.="'".$value."',";
        }
        $str = substr($str,0,strlen($str)-1);
        $str .= '))';

        return $str;
    }

    /**
     * 查询确认收入&收入&合同
     * 相同结转期的收入
     * @param \common\models\myhtsq\RevenueRecognitionModel $revenueRecognitionModel
     * @return array
     */
    public static function getRecognitionRevenueContractByDate($revenueRecognitionModel)
    {
        //当前激活结转期
        $recognitionDate =RevenueRecognitionDateRepository::getRecognitionDateNew();

        $thisRecognitionBegin = self::dateToYmd($recognitionDate['recognition_begin']);
        $thisRecognitionEnd = self::dateToYmd($recognitionDate['recognition_end']);

        $where = '1=1';
        $whereSql = self::__buildGetRecognitionRevenueContractWhereSql($where,$revenueRecognitionModel);
        $query = new Query();
        $result = $query->select([
                                'account_company.account_company_name,contract_company.company_name,revenue.income_code,manage.contract_code,
                                manage.customer_full_name,manage.sign_date,manage.input_date,recognition.recognition_begin,manage.sign_amount,property.property_name,
                                big_category.big_category_name,littler_category.littler_category_name,revenue_types.type_name,revenue_types.finance_type_name,
                                revenue.amount,revenue.establish_time,revenue_types.finance_type_name,
                                (
                                    CASE revenue_types.finance_type_name
                                    WHEN "云客增值服务收入项" THEN
                                        "一次性确认"
                                    WHEN "云客租用服务收入项" THEN
                                        "按照租期确认"
                                    WHEN "云客互联网服务收入项" THEN
                                        "待定"
                                    ELSE
                                        "其他"
                                    END
                                ) AS recognition_type,
                                revenue.begin_on,revenue.end_on,recognition.recognition_end,
                                revenue.unrecognized_bad_debt_amount,revenue.recognized_bad_debt_amount,revenue.kingdee_bad_debt_amount,
                                recognition.recognition_date AS recognition_time,recognition.revenue_id,manage.is_cancelled,manage.contract_status,revenue.close_status          
                                '
            ])
            ->from('myscrm_contract_revenue AS revenue')
            ->leftJoin('myscrm_revenue_recognition AS recognition','recognition.revenue_id = revenue.revenue_id')
            ->leftJoin('myscrm_contract_manage AS manage','manage.contract_id = recognition.contract_id')
            ->leftJoin('myscrm_contract_property AS property','manage.contract_property_id = property.property_id')
            ->leftJoin('myscrm_contract_big_category AS big_category','manage.big_category_id = big_category.big_category_id')
            ->leftJoin('myscrm_contract_littler_category AS littler_category','manage.littler_category_id = littler_category.littler_category_id')
            ->leftJoin('myscrm_buss_account_types revenue_types','revenue_types.type_id = revenue.revenue_type')
            ->leftJoin('myscrm_contract_account_company AS account_company','account_company.account_company_id = manage.account_company_id')
            ->leftJoin('myscrm_contract_company AS contract_company','manage.company_id = contract_company.company_id')
            ->where(['recognition.is_del'=>1,'manage.is_cancelled'=>0,'manage.contract_status'=>2])
            ->andwhere($whereSql['where'], $whereSql['params'])
            ->all(ContractEntity::getDb());

        //增加上期累计确认收入&本期累计确认收入&缺少收入来源判断
        foreach ($result as &$item){

            //依据大于等当前结转期之后的进行汇总
            #结转末期相同汇总但是结转初期是否有可能不同算做不同结转期？这样逻辑有问题
            $revenueId = $item['revenue_id'];
            $recognitionEnd = $item['recognition_end'];

            $issueTotalRecognitionAmountAfterThis = self::summaryRecognitionAmountAfterThis($revenueId,$recognitionEnd);
            $getRecognitionBeforeThisRecognitionEnd = self::getRecognitionBeforeThisRecognitionEnd($revenueId,$recognitionEnd);
            $totalRecognitionAmount = self::summaryRecognitionAmount($item['revenue_id']);

            //收入下所有结转金额汇总 - 当前结转期之后的进行汇总 = 上期累计汇总
            $lastIssueTotalRecognitionAmount = $totalRecognitionAmount - $issueTotalRecognitionAmountAfterThis;
            $thisRecognitionAmount = ContractRevenueRepository::getThisRecognitionAmount($item['revenue_id'],$thisRecognitionBegin,$thisRecognitionEnd);
            $thisTotalRecognitionAmount = $lastIssueTotalRecognitionAmount+$thisRecognitionAmount;

            $item['last_total_recognition_amount'] = $lastIssueTotalRecognitionAmount;
            $item['this_recognition_amount'] = $thisRecognitionAmount;
            $item['this_total_recognition_amount'] = $thisTotalRecognitionAmount;
            $item['revenue_unrecognized_amount'] = $item['amount'] - $thisTotalRecognitionAmount;//本期剩余
            $item['this_total_recognition_excluding_tax_amount'] = $thisTotalRecognitionAmount/1.06;
            $item['total_recognition_amount'] = $lastIssueTotalRecognitionAmount + $item['recognition_amount'];
            $item['revenue_source'] = empty($getRecognitionBeforeThisRecognitionEnd)?'本期新增':'上期结转';

        }

        return $result;

    }

    public static function getRecognitionRevenueContractPageByDate($result,$pageIndex,$pageSize = 20,$order = 0)
    {

        //数组分页
        $resultPage = self::pageArray($pageSize,$pageIndex,$result,$order);
        $result = [
            'total'=>count($result),
            'items'=>$resultPage,
        ];

        return $result;
    }


    /**
     * 查询确认收入&收入&合同
     * @param string $recognitionBegin 开始日期
     * @param string $recognitionEnd 结束日期
     * @return array
     */
    public static function getRevenueReceivablePaymentListByDate($revenueRecognitionModel)
    {
        //当前激活结转期
        $recognitionDate =RevenueRecognitionDateRepository::getRecognitionDateNew();

        $thisRecognitionBegin = self::dateToYmd($recognitionDate['recognition_begin']);
        $thisRecognitionEnd = self::dateToYmd($recognitionDate['recognition_end']);

        $where = '1=1';
        $whereSql = self::__buildGetRecognitionRevenueContractWhereSql($where,$revenueRecognitionModel);
        $query = new Query();
        //缺少最后结转期&缺少合同下财务收入项相同的应收&与这些应收关联的回款&缺少累计收入金额
        $result = $query->select([
            '
                contract_company.company_name,manage.contract_code,manage.customer_full_name,
                manage.sign_date,manage.input_date,
                (
                    CASE property.from_finance
                    WHEN "1" THEN
                        "直销合同"
                    WHEN "2" THEN
                        "分销合同"    
                    ELSE
                        "其他"
                    END
                ) AS contract_finance_property,
                (
                    CASE property.from_performance_finance
                    WHEN "1" THEN
                        "直销合同"   
                    WHEN "2" THEN
                        "分销合同"    
                    ELSE
                        "其他"
                    END
                ) AS contract_performance_finance_property, 
                big_category.big_category_name,littler_category.littler_category_name,revenue.income_code,revenue_types.type_name,
                revenue_types.finance_type_name,revenue.amount,recognition.recognition_begin,recognition.recognition_date,recognition.revenue_id,
                manage.sign_amount,property.property_name,property.from_finance,property.from_performance_finance,
                revenue_types.finance_type_name,revenue.begin_on,revenue.end_on,recognition.recognition_end,manage.sign_people_abu_name,
                revenue.unrecognized_bad_debt_amount,revenue.recognized_bad_debt_amount,revenue.kingdee_bad_debt_amount,
                revenue.revenue_type,manage.contract_id
            '
        ])
            ->from('myscrm_contract_revenue AS revenue')
            ->leftJoin('myscrm_revenue_recognition AS recognition','recognition.revenue_id = revenue.revenue_id')
            ->leftJoin('myscrm_contract_manage AS manage','manage.contract_id = revenue.contract_id')
            ->leftJoin('myscrm_contract_property AS property','manage.contract_property_id = property.property_id')
            ->leftJoin('myscrm_contract_big_category AS big_category','manage.big_category_id = big_category.big_category_id')
            ->leftJoin('myscrm_contract_littler_category AS littler_category','manage.littler_category_id = littler_category.littler_category_id')
            ->leftJoin('myscrm_buss_account_types revenue_types','revenue_types.type_id = revenue.revenue_type')
            ->leftJoin('myscrm_contract_company AS contract_company','manage.company_id = contract_company.company_id')
            ->where(['recognition.is_del'=>1,'manage.is_cancelled'=>0,'manage.contract_status'=>2])
            ->andwhere($whereSql['where'], $whereSql['params'])
            ->all(ContractEntity::getDb());

        foreach ($result as &$item){

            $revenueRecognitionList = self::getRevenueRecognitionListByRevenueId($item['revenue_id']);

            //确定合同下收入与应收的关系
            $receivables = ContractReceivableRepository::getReceivableByContractIdRevenueType($item['contract_id'],$item['revenue_type']);
            //汇总被确定的应收金额
            $summaryReceivableAmount = self::summaryReceivableAmount($receivables);

            //应收找应收发票关系


            //依据应收汇总回款
            $summaryPaymentAmount = self::summaryPaymentAmount($receivables);

            $recognition_ends = [];
            foreach ($revenueRecognitionList as $record){
                $recognition_ends[] = $record['recognition_end'];
            }

            $thisRecognitionAmount = ContractRevenueRepository::getThisRecognitionAmount($item['revenue_id'],$thisRecognitionBegin,$thisRecognitionEnd);
            $item['this_recognition_amount'] = $thisRecognitionAmount;//本期收入金额
            $item['total_recognition_amount'] = self::summaryRecognitionAmount($item['revenue_id']);//累计确认收入

            //根据所属收入项,取应收款中财务收入项等于该收入项的应收款.取不到则为空
            $item['this_receivable_amount'] = $summaryReceivableAmount;//应收款金额
            $item['this_payment_amount'] = $summaryPaymentAmount;//本期回款  取前面所获得的应收款的在所属期间内的回款
            $item['summary_payment_amount'] = $summaryPaymentAmount;//累计回款  取前面所获得的应收款的截止目前的回款
            $item['last_recognition_end'] = max($recognition_ends);//最后结转期间

            if(empty($item['amount'])){
                $item['remark'] = '该收入项金额为0或者空无法确定收入金额';
            }
            
        }
        return $result;
    }


    /**
     * 一次性确认收入
     * @param string $recognitionNow 当前结转期
     * @return array
     */
    public static function revenueRecognitionRecordByDisposables($revenueList){
        $recognitionDate = RevenueRecognitionDateRepository::getRecognitionDateNew();
        return self::revenueRecognitionRecord($recognitionDate['recognition_begin'],$recognitionDate['recognition_end'],$revenueList,'云客增值服务收入项');
    }

    /**
     * 一次性确认收入 (广告)
     * @param string $recognitionNow 当前结转期
     * @return array
     */
    public static function revenueRecognitionRecordByAd($revenueList){
        $recognitionDate = RevenueRecognitionDateRepository::getRecognitionDateNew();
        return self::revenueRecognitionRecord($recognitionDate['recognition_begin'],$recognitionDate['recognition_end'],$revenueList,'云客互联网服务收入项');
    }

    /**
     * 转结全部收入
     * @param string $revenueList 当前结转期
     * @return array
     */
    public static function revenueRecognitionRecordAll($revenueList){
        $recognitionDate = RevenueRecognitionDateRepository::getRecognitionDateNew();
        return self::revenueRecognitionRecord($recognitionDate['recognition_begin'],$recognitionDate['recognition_end'],$revenueList,false);
    }

    /**
     * 按照租期确认收入
     * 云客租用服务收入项
     * @param string $recognitionBegin
     * @param string $recognitionEnd
     * @param string $isNotClosedRevenueAllParams
     * @return array
     */
    public static function revenueRecognitionRecordByPeriods($revenueList){
        $recognitionDate = RevenueRecognitionDateRepository::getRecognitionDateNew();
        return self::revenueRecognitionRecord($recognitionDate['recognition_begin'],$recognitionDate['recognition_end'],$revenueList,'云客租用服务收入项');
    }

    /**
     * 获取当前租期
     * @return array
     */
    public static function getRecognitionDate()
    {
        return RevenueRecognitionDateRepository::getRecognitionDate();
    }

    /**
     * 获取当前租期新
     * @return array
     */
    public static function getRecognitionDateNew()
    {
        return RevenueRecognitionDateRepository::getRecognitionDateNew();
    }

    public static function getRecognitionListDate()
    {
        return RevenueRecognitionDateRepository::getRecognitionListDate();
    }

    public static function getRecognitionListDateByTime($recognitionBegin,$recognitionEnd)
    {
        return RevenueRecognitionDateRepository::getRecognitionListDateByTime($recognitionBegin,$recognitionEnd);
    }

    /**
     * 设置新租期
     * @return boolean|string 失败返回false，成功返回收入期Id
     */
    public static function setRecognitionDate($revenueRecognitionModel)
    {
        return RevenueRecognitionDateRepository::setRecognitionDate($revenueRecognitionModel);
    }

    /**
     * 获取最新结转人
     */
    public static function getRecentRecognitionUser()
    {
        return RevenueRecognitionEntity::find()->select('recognition_by,recognition_date')->where(['is_del'=>1])->orderBy(['recognition_date' => SORT_DESC])->one();
    }

    /**
     * 获取最新结转人
     */
    public static function getRecognitionList($revenueId,$recognitionBegin,$recognitionEnd)
    {
        return RevenueRecognitionEntity::find()->where(['is_del'=>1,'revenue_id'=>$revenueId,'recognition_begin'=>$recognitionBegin,'recognition_end'=>$recognitionEnd])->all();
    }

    /**
     * 获取本期结转信息
     * @param $revenueId
     * @param $recognitionBegin
     * @param $recognitionEnd
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getTermRecognition($revenueId,$recognitionBegin,$recognitionEnd){
        return RevenueRecognitionEntity::find()->where(['is_del'=>1,'revenue_id'=>$revenueId,'recognition_begin'=>$recognitionBegin,'recognition_end'=>$recognitionEnd])->one();
    }

}